﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;

namespace Server
{
    class CommandHandler
    {
        //private bool running;
        private Socket clientSocket;
        private Message protocolMessage;
        private UserHandler userHandler;
        //private FileThread fileThread;

        public CommandHandler(Socket client)
        {
          //  running = true;
            clientSocket = client;
            userHandler = new UserHandler(clientSocket);
            protocolMessage = new Message();
        }


        public void handleCommand(string[] message)
        {

            if (message[0] == "$FRANK")
            {
                if (message[1] == "FILE")
                {
                    //fileThread = new FileThread();
                    //Thread threadFile = new Thread(new ParameterizedThreadStart(fileThread.fileHandle));
                    //threadFile.Name = "FileThread";
                    //threadFile.Start(message);
                    //fileThread.StartFileListening(message);



                    //while (threadFile.IsAlive != true)
                    //{
                    //    System.Diagnostics.Debug.WriteLine("File Thread not started");
                    //    Thread.Sleep(5);
                    //}
                    Thread.Sleep(100);
                    if (message[2] == "UPLOAD")
                    {
                        
                        protocolMessage.sendMessage(clientSocket, "$FRANK,FILE,UPLOAD,START,");

                    }
                    if (message[2] == "DOWNLOAD")
                    {
                        protocolMessage.sendMessage(clientSocket, "$FRANK,FILE,DOWNLOAD,START,");
                    }
                    //fileThread.StartFileListening(message);
                }
                else if (message[1] == "USER")
                {
                    if (userHandler.handleUser(message) == true)
                    {
                        protocolMessage.sendMessage(clientSocket, "$FRANK,USER,OK,");
                    }
                    else
                    {
                        protocolMessage.sendMessage(clientSocket, "$FRANK,USER,BAD,");
                    }
                }
                else if (message[1] == "CLIENT")
                {
                    if (message[2] == "DIS")
                    {
                        protocolMessage.sendMessage(clientSocket, "$FRANK,USER,DISC,");
                        Thread.Sleep(10);
                        clientSocket.Disconnect(true);
                        clientSocket.Close();
                    }
                }
            }
        }
    }
}
